package minjre.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-05-28 16:32
 */
public class CommandUtils {

    /**
     * 执行cmd指令
     * @param charsetName 字符集
     * @param lineFeed 是否换行
     * @param args 参数
     * @return
     */
    public static StringBuffer doCommand(String charsetName, boolean lineFeed, String... args){
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(args);
        processBuilder.redirectErrorStream(true);
        try {
            Process process = processBuilder.start();
            InputStream inputStream = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            String line = "";
            StringBuffer buffer = new StringBuffer();
            while((line = br.readLine()) != null){
                buffer.append(line.trim());
                if(lineFeed){
                    buffer.append("\n");
                }
            }

            return buffer;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new StringBuffer();
    }
}
